package com.az.rediscommon.util;

import com.az.miaoapi.exception.BusyLockException;
import lombok.Data;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

@Data
public class RedissonLockUtil {
    private RedissonLockUtil(){}
    private static RedissonLockUtil instance;
    public static synchronized RedissonLockUtil getInstance() {
        if (instance == null) {
            instance = new RedissonLockUtil();
        }
        return instance;
    }

    private RedissonClient redissonClient;

    public void lock(String key) {
        if (redissonClient == null) {
            throw new NullPointerException("RedissonClient不存在");
        }
        RLock lock = redissonClient.getLock(key);
        try {
            if (!lock.tryLock(3L, 30L, TimeUnit.SECONDS)) {
                throw new BusyLockException();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
    }

    public void unLock(String key) {
        redissonClient.getLock(key).unlock();
    }
}
